const { setSocket } = require("../utils/msgSave");
const TcpClient = require("./tcpClient");
const {
  initIp,
  getIps,
  ipForClient,
  changeIpStatus,
} = require("../utils/handleIp");

const tcpClients = [];

let title = "相机信息";
let eventName = "clientHandle";
let setIntervalTimer = null;

async function tcpSocketInfo(socketInstance) {
  if (!socketInstance) {
    return;
  }
  socketInstance.on("connection", async (socket) => {
    console.log("client tcp WebSocket连接成功");
    // 销毁所有现有的 TCP 客户端
    if (tcpClients.length > 0) {
      tcpClients.forEach((client) => {
        client.destroy();
      });
      tcpClients.length = 0;
      // 清除定时器
      if (setIntervalTimer) {
        clearInterval(setIntervalTimer);
        setIntervalTimer = null;
      }
    }
    console.log("tcpClients====", tcpClients.length);
    try {
      getTcpList(socket);
    } catch (error) {}
  });
  // socket 断开连接
  socketInstance.on("disconnect", () => {
    console.log("client tcp WebSocket连接断开");
  });
}

async function handleTcpClientEvents(client, socket) {
  // 连接成功
  client.on("connected", async (data) => {
    // console.log("tcp connect", data);
    let changeFlag = await changeIpStatus(data);

    const content = `应用给流水线${data.beUsed}且ip是${data.ip},端口是${data.port}的相机客户端,连接成功`;

    const dataStr = {
      id: data.id,
      data: data.data,
      ip: data.ip,
      port: data.port,
      type: data.type,
      status: data.status,
      beUsed: data.beUsed,
      MAX_RECONNECT_ATTEMPTS: data.MAX_RECONNECT_ATTEMPTS / 1 - 1,
    };

    await setSocket(
      socket,
      title + "-连接",
      content,
      data.ip,
      JSON.stringify(dataStr),
      eventName
    );
  }); // 连接失败
  client.on("error", async (data) => {
    await changeIpStatus(data);
    const content = `应用给线体${data.beUsed}的，且ip是${data.ip},端口是${data.port}的相机客户端,连接失败`;
    await setSocket(
      socket,
      title,
      content,
      data.ip,
      JSON.stringify(data),
      eventName
    );
  });
  // 断开连接
  client.on("disconnect", async (data) => {
    await changeIpStatus(data);
    const content = `${data.ip},端口${data.port}的TCP客户端,断开连接`;
    await setSocket(
      socket,
      title,
      content,
      data.ip,
      JSON.stringify(data),
      eventName
    );
  });
  // 接收数据
  client.on("data", async (data) => {
    console.log("data====", data);
    const content = `${client.ip},端口${client.port}的TCP客户端,接收数据成功`;
    const dataStr = {
      id: data.id,
      data: data.data,
      ip: data.ip,
      port: data.port,
      type: data.type,
      status: data.status,
      beUsed: data.beUsed,
      MAX_RECONNECT_ATTEMPTS: data.MAX_RECONNECT_ATTEMPTS / 1 - 1,
    };

    await setSocket(
      socket,
      title + "-接收消息",
      content,
      client.ip,
      JSON.stringify(dataStr),
      eventName
      //  routParams
    );
    socket.emit("tcpData", {
      message: "tcp data success",
      data: data,
    });
  });
}
// 获取使用tcp【相机】 连接的地址
async function getTcpList(socket) {
  const { count, rows } = await getIps(1);
  if (count === 0) {
    return;
  }
  //console.log("相机的ip地址====", count, rows);
  // 将ip 地址的状态都改成未连接状态
  const flagInitIp = await initIp(1);

  if (flagInitIp) {
    console.log("初始化ip状态成功");
  } else {
    console.log("初始化ip状态失败");
    return;
  }

  // 获取ip 数组
  const ipListForClient = await ipForClient(count, rows);
  //console.log("ipListForClient====", ipListForClient)
  if (ipListForClient.length === 0) {
    return;
  }
  // 连接tcp
  ipListForClient.forEach((item) => {
    const { id, ip, port, type, status, beUsed } = item;
    const isTcpClient = tcpClients.find((c) => c.id == id);

    if (isTcpClient) {
      return;
    } else {
      const client = new TcpClient(ip, port, id, type, status, beUsed);

      tcpClients.push(client);
      handleTcpClientEvents(client, socket);
    }
  });
  // console.log("tcpClients====", tcpClients)
}

module.exports = {
  tcpClients,
  tcpSocketInfo,
};
